<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="70px" class="custom-form">

        <el-form-item class="input_st" label="会员名" prop="fullName">
          <el-input
              v-model="queryParams.fullName"
              placeholder="请输入会员名"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item class="input_st" label="联系电话" prop="phone">
          <el-input
              v-model="queryParams.phone"
              placeholder="请输入联系电话"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item class="input_st" label="性别" prop="gender">
          <el-select v-model="queryParams.gender" placeholder="请选择" clearable>
            <el-option
                v-for="dict in sys_user_sex"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="input_st" label="账户状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择" clearable>
            <el-option
                v-for="dict in m_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="date-range-item" label="注册时间">
          <el-date-picker
              v-model="daterangeCreateTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="getDateStr()"
          ></el-date-picker>
        </el-form-item>
        <el-form-item class="form-buttons">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8 operation-bar">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:members:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['system:members:import']">导入</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:members:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格区域 -->
    <div v-if="membersList.length===0" class="empty-container">
      <el-empty description="暂无会员数据" />
    </div>
    <div v-else class="table-container">
      <el-table
          height="500"
          v-loading="loading"
          element-loading-text="数据正在加载中,请稍后......"
          :element-loading-spinner="svg"
          element-loading-svg-view-box="-10, -10, 50, 50"
          element-loading-background="rgba(122, 122, 122, 0.8)"
          border
          :data="membersList"
          @selection-change="handleSelectionChange"
          class="custom-table"
          :row-class-name="tableRowClassName"
          style="width: 100%">
        <el-table-column type="selection"  width="55" align="center" />
        <el-table-column type="index" label="序号 " width="60" align="center"   :index="indexMethod" />
        <el-table-column label="会员全名" align="center" prop="fullName" sortable  />
        <el-table-column label="联系电话" align="center" prop="phone" sortable  >
          <template #default="scope">
            <el-icon><Iphone /></el-icon>{{scope.row.phone}}
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" prop="gender" sortable>
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.gender"/>
          </template>
        </el-table-column>
        <el-table-column label="积分余额" align="center" prop="pointsBalance" sortable  >
          <template #default="scope">
            ￥{{scope.row.pointsBalance}}
          </template>
        </el-table-column>
        <el-table-column label="账户状态" align="center" prop="status" sortable >
          <template #default="scope">
            <el-switch
                :model-value="scope.row.status"
                @update:model-value="scope.row.status = $event; handleStatusChange(scope.row)"
                active-text="激活"
                inactive-text="禁用"
                inline-prompt
                :active-value="'0'"
                :inactive-value="'1'"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注信息"  align="center" prop="remark" sortable  show-overflow-tooltip />
        <el-table-column label="注册时间" align="center" prop="createTime" width="170" wsortable >
          <template #default="scope">
            <span><el-icon><timer /></el-icon>{{ parseTime(scope.row.createTime,  '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最近一次结算时间" align="center" prop="updateTime" width="170" sortable >
          <template #default="scope">
            <span><el-icon><timer /></el-icon>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}  {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createBy" sortable />
        <el-table-column label="修改人" align="center" prop="updateBy" sortable />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  fixed="right" v-hasPermi="['system:members:remove']">
          <template #default="scope">
            <el-button link type="warning" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:members:edit']">修改</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:members:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        class="custom-pagination"
    />

    <!-- 添加或修改系统会员信息对话框 -->
    <el-dialog draggable   destroy-on-close center :close-on-click-modal="false" :close-on-press-escape="false" :title="title"  v-model="open" width="500px" append-to-body class="custom-dialog">
      <el-form ref="membersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="会员全名" prop="fullName">
          <el-input :disabled="disabled" v-model="form.fullName" placeholder="请输入会员全名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio
                v-for="dict in sys_user_sex"
                :key="dict.value"
                :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="积分余额" prop="pointsBalance">
          <el-input type="number" :min="0" v-model="form.pointsBalance" placeholder="请输入积分余额" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 用户导入对话框 -->
  <el-dialog  destroy-on-close center :close-on-click-modal="false" :close-on-press-escape="false" draggable :title="upload.title" v-model="upload.open" width="400px" append-to-body>
    <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-change="handleFileChange" :on-remove="handleFileRemove" :auto-upload="false" drag>
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <div class="el-upload__tip">
            <el-checkbox disabled v-model="upload.updateSupport" />是否更新已经存在的会员数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"  v-hasPermi="['system:members:import']"  @click="importTemplate">下载模板</el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <!--导出excel/pdf-->
  <el-dialog  destroy-on-close center :close-on-click-modal="false" :close-on-press-escape="false" draggable title="您正在导出会员基本信息"
              v-model="eOrp" width="400px" append-to-body>
    <el-form ref="membersRef" :rules="rules"  :inline="true" label-position="top" label-width="auto">
      <el-form-item label="类型">
        <el-select v-model="queryParams.eOrp" placeholder="请选择" style="width: 190px">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>

      </el-form-item>

      <el-form-item label="文件名称" prop="fileName">
        <el-input v-model="queryParams.fileName"  clearable placeholder="请输入文件名称"/>
      </el-form-item>
      <el-form-item label="条数" >
        <el-radio-group v-model="queryParams.pageSize" size="large" fill="#6cf"  >
          <el-radio-button label="前50条" :value="50" />
          <el-radio-button label="前100条" :value="100" />
          <el-radio-button label="前1000条" :value="1000" />
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button @click="exportInfo" v-hasPermi="['system:members:export']"  style="margin-left:20rem" type="primary">导出</el-button>
      </el-form-item>

    </el-form>
  </el-dialog>
</template>

<script setup name="Members">
import { listMembers, getMembers, delMembers, addMembers, updateMembers } from "@/api/system/members"
import { getToken } from "@/utils/auth"
import {getDateStr,indexMethod,tableRowClassName} from "@/utils/ruoyi.js"
const { proxy } = getCurrentInstance()
const { m_status, sys_user_sex } = proxy.useDict('m_status', 'sys_user_sex')
const membersList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const disabled=ref(false);

// // 格式化日期时间为 "YYYY-MM-DD HH:mm:ss" 格式
// const formatDateTime = (date) => {
//   const year = date.getFullYear();
//   const month = String(date.getMonth() + 1).padStart(2, '0');
//   const day = String(date.getDate()).padStart(2, '0');
//   const hours = String(date.getHours()).padStart(2, '0');
//   const minutes = String(date.getMinutes()).padStart(2, '0');
//   const seconds = String(date.getSeconds()).padStart(2, '0');
//
//   return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
// };
//
// // 获取当前日期
// const today = new Date();
//
// // 当天00:00:00
// const startOfDay = new Date(today);
// startOfDay.setHours(0, 0, 0, 0);
//
// // 当天23:59:59
// const endOfDay = new Date(today);
// endOfDay.setHours(23, 59, 59, 999);
//
// // 设置默认时间范围为当天0点到23点59分59秒
// const daterangeCreateTime = ref([
//   formatDateTime(startOfDay),
//   formatDateTime(endOfDay)
// ]);
const daterangeCreateTime = ref([]);

const eOrp=ref(false)

const options=ref([
  {
    value: '1',
    label:"EXCEL",
    key: 'excel',
  },
  {
    value: '2',
    label:"PDF",
    key: 'pdf',
  }
])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    id: null,
    fullName: null,
    phone: null,
    gender: null,
    pointsBalance: null,
    status: null,
    remark: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    delFlag: null,
    eOrp: null,
    fileName:null,
  },
  rules: {
    id: [
      { required: true, message: "会员唯一标识ID不能为空", trigger: "blur" }
    ],
    fullName: [
      { required: true, message: "会员全名不能为空", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" }
    ],
    gender: [
      { required: true, message: "性别不能为空", trigger: "change" }
    ],
    pointsBalance: [
      { required: true, message: "积分余额不能为空", trigger: "blur" }
    ],
    fileName:[
      { required: true, message: "文件名称不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: true,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/members/importData"
})
/** 查询系统会员信息列表 */
function getList() {
  membersList.value=[];
  loading.value = true

  if (null != daterangeCreateTime.value) {
    queryParams.value.beginCreateTime = daterangeCreateTime.value[0]
    queryParams.value.endCreateTime = daterangeCreateTime.value[1]
  }else {
    queryParams.value.beginCreateTime = null
    queryParams.value.endCreateTime = null
  }
  listMembers(queryParams.value).then(response => {
    if (response.code === 200) {
      membersList.value = response.rows
      total.value = response.total
    }
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    fullName: null,
    phone: null,
    gender: null,
    pointsBalance: null,
    status: null,
    remark: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    delFlag: null,
    eOrp: null,
    fileName:null,
  }
  proxy.resetForm("membersRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1

  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = []
  proxy.resetForm("queryRef")
  queryParams.value.pageSize=10
  handleQuery()
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加系统会员信息"
  disabled.value=false;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getMembers(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改系统会员信息"
    disabled.value = true
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["membersRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMembers(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMembers(form.value).then(response => {
          if (response.code == 200) {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          }
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {

  proxy.$modal.confirm('是否确认删除系统会员为"' + row.fullName + '"的数据项？').then(function() {
    return delMembers(row.id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  queryParams.value.pageSize=50
  queryParams.value.fileName="会员信息_"+new Date().getTime()
  queryParams.value.eOrp="1"
  eOrp.value=true

}
const exportInfo=()=>{
  let name=null;
  if (queryParams.value.eOrp==="1"){
    name=  queryParams.value.fileName+".xlsx"
  }else {
    name=  queryParams.value.fileName+".pdf"
  }
  queryParams.value.fileName=name
  proxy.download('system/members/export', {
    ...queryParams.value
  },queryParams.value.fileName)
  eOrp.value=false;
}

getList()
// 处理状态切换
const handleStatusChange = (row) => {
  let flag = row.status === '1' //保存点击之后v-modeld的值(true，false)
  //保持switch点击前的状态
  row.status = flag ? '0' :'1'
  proxy.$modal.confirm('您确定操作'+row.fullName+'会员'+(row.status === '0' ? '禁用' : '激活')+'操作吗', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    flag ? row.status = '1' : row.status = '0'//还原原来点击过的值

    updateMembers(row).then(response => {
      if (response.code === 200) {
        proxy.$modal.msgSuccess(response.msg)
        getList()
      }else {
        proxy.$modal.msgSuccess(response.msg)
      }
    })

  }).catch(() => {
    proxy.$modal.msgWarning({ type: 'info', showClose: true, message: '已取消修改！' })
  });
};
/** 导入按钮操作 */
function handleImport() {
  upload.title = "会员信息导入"
  upload.open = true
  upload.selectedFile = null
}

/** 下载模板操作 */
function importTemplate() {

  proxy.download('system/members/export', {
    fullName: "模糊",
    eOrp:"1"
  }, `members_${new Date().getTime()}.xlsx`)
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件选择处理 */
const handleFileChange = (file, fileList) => {
  upload.selectedFile = file
}

/** 文件删除处理 */
const handleFileRemove = (file, fileList) => {
  upload.selectedFile = null
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
  getList()
}

/** 提交上传文件 */
function submitFileForm() {
  const file = upload.selectedFile
  if (!file || file.length === 0 || !file.name.toLowerCase().endsWith('.xls') && !file.name.toLowerCase().endsWith('.xlsx')) {
    proxy.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
    return
  }
  proxy.$refs["uploadRef"].submit()
}

</script>
<style scoped >

/* 整体布局样式 */
.app-container {
  padding: 20px;
  background-color: #f5f7f9;

}

/* 搜索区域样式 */
.search-area {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
}

.custom-form {
  display: flex;
  flex-wrap: wrap;
  gap: 9px;
  align-items: flex-start;
}

.custom-form :deep(.el-form-item) {
  margin-bottom: 0;
  display: flex;
  align-items: center;
}

.custom-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  width: 80px;
  text-align: right;
  flex-shrink: 0;
}

.custom-form :deep(.el-form-item__content) {
  flex: 1;
  min-width: 0;
}

.input_st {
  width: 200px;
  flex-shrink: 0;
}

.date-range-item {
  width: 425px;
}

.form-buttons {
  margin-left: auto;
  align-self: center;
  flex-shrink: 0;
}

/* 操作按钮区域样式 */
.operation-bar {
  background: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

/* 表格容器样式 */
.table-container {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 15px;
}

/* 表格样式 */
.custom-table {
  border-radius: 4px;
  overflow: hidden;
}

.custom-table :deep(th) {
  background-color: #f8f9fa !important;
  color: #495057;
  font-weight: 600;
  height: 50px;
}

.custom-table :deep(td) {
  padding: 12px 0;
  height: 54px;
}

.custom-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.custom-table :deep(.el-table__row--striped) {
  background-color: #fafafa;
}

.custom-table :deep(.el-table__row--striped:hover) {
  background-color: #f5f7fa;
}

/* 隐藏表格滚动条 */
.table-container :deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 0 !important;
  height: 0 !important;
  display: none;
}

.table-container :deep(.el-table__body-wrapper) {
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/* 空数据样式 */
.empty-container {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 40px 0;
  margin-bottom: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

/* 分页样式 */
.custom-pagination {
  background: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: flex-end;
}

/* 对话框样式 */
.custom-dialog :deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #e8e8e8;
  margin-right: 0;
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 30px 20px;
}

.custom-dialog :deep(.el-form-item) {
  margin-bottom: 22px;
}

.custom-dialog :deep(.el-input__inner) {
  height: 38px;
  line-height: 38px;
}

.custom-dialog :deep(.el-textarea__inner) {
  min-height: 80px;
}

.dialog-footer {
  padding-top: 10px;
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 1400px) {
  .input_st {
    width: 180px;
  }

  .date-range-item {
    width: 350px;
  }
}

@media (max-width: 1200px) {
  .input_st {
    width: 160px;
  }

  .date-range-item {
    width: 320px;
  }
}

@media (max-width: 992px) {
  .custom-form {
    flex-direction: column;
    align-items: stretch;
  }

  .input_st, .date-range-item {
    width: 100%;
  }

  .form-buttons {
    margin-left: 0;
    align-self: flex-start;
  }

  .custom-form :deep(.el-form-item) {
    flex-direction: column;
    align-items: flex-start;
  }

  .custom-form :deep(.el-form-item__label) {
    width: 100%;
    text-align: left;
    margin-bottom: 8px;
  }
}

.el-table /deep/ .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table /deep/ .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
/* 渐变边框 */
.el-input__inner{
  border-image:linear-gradient(to right,#000718,#23b7cb) 5 5!important;
  /* 自定义其他样式时 注意加 !important 安全一些 */
}



</style>